//from PSID: proportion of people who move from periods 2-3, and proportion who move back home
use "$temp/psid_long_cleaned", clear
keep uniqid statefips birth_state weight age
keep if age<=54

//age groups
gen age_group = 1
replace age_group = 2 if age>=36

//limit to people observed in both age groups
gen count = 1
bys uniqid age_group: egen total_obs = total(count) //times observed for each period
bys uniqid: egen min_obs = min(total_obs) //smaller count of the two
drop if min_obs<6 //observed less than 6 years for either rperiod. Doesn't catch people not observed in a gven period at all; take care of that later.

//modal state in periods 2, 3
bys uniqid age_group: egen state_mode = mode(statefips) //modal state in each pedriod
gen flag_miss = (state_mode == .) 
bys uniqid: egen flag_drop = max(flag_miss)
drop if flag_miss == 1 //drop if missing

//cruedely reshape to wide format
sort uniqid age_group
gen temp = state_mode if age_group==1
bys uniqid: egen state1 = max(temp)
drop temp

gen temp = state_mode if age_group==2
bys uniqid: egen state2 = max(temp)
drop temp

drop if state1 == . | state2 == . //this kills people observed in only one period

//collapse to individual level
collapse (first) birth_state state1 state2 (mean) weight, by(uniqid)
keep uniqid birth_state state1 state2 weight
duplicates drop uniqid, force
drop if birth_state==.

//fraction of movers
gen mig1 = (state1!=birth_state)
gen mig2 = (state1!=state2)
gen mig_home = (state1!=state2 & state2 == birth_state)

//moving statistics
//su mig1 [w=weight] //not really comparable; don't worry about this
set seed 1234

qui{
	forval i = 1/1000{
		preserve
	
		if mod(`i', 20)==0{
			noi di as result "`i'"
		}
		
		bsample
		su mig2 [w=weight] //16% move in between period 1 and 2, so a lot less than in the first phasec
		clear
		set obs 1
		gen moment = `r(mean)'
		save "$temp/boot/mig_dynamic_boot_`i'", replace
		restore
	}
	
}


clear
forval i = 1/1000{
	append using "$temp/boot/mig_dynamic_boot_`i'"
}
export delimited "$dir/Model/boot/mig_dynamic_boot_sample.csv", novarn replace
